package com.example.study.page.fragment

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.study.ListViewModel
import com.example.study.databinding.FragmentOkHttpBinding
import com.example.study.source.CustomOkHttpClient
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Request
import okhttp3.Response
import java.io.IOException


class OkHttpFragment : Fragment() {
    companion object {
        const val URL = "https://t7.baidu.com/it/u=4069854689,43753836&fm=193&f=GIF"
    }

    private lateinit var binding: FragmentOkHttpBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = FragmentOkHttpBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val viewModel = ViewModelProvider(this)[ListViewModel::class.java]
        binding.progressBar.setIndicatorColor(Color.CYAN)
        binding.progressBar.show()
        viewModel.okHttpProgress.observe(viewLifecycleOwner) {
            binding.text.text = "$it%"
            binding.progressBar.progress = it
            if (it == 100) {
                binding.progressBar.hide()
            }
        }
        val client = CustomOkHttpClient(object : CustomOkHttpClient.ProgressListener {
            override fun onProgress(progress: Int) {
                viewModel.okHttpProgress.postValue(progress)
            }
        }).client()


        client.newCall(Request.Builder().url(URL).build())
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                }

                override fun onResponse(call: Call, response: Response) {
                    response.body()?.byteStream()?.use { input ->
                        val buffer = ByteArray(4096)
                        var bytesRead: Int
                        while (input.read(buffer).also { bytesRead = it } != -1) {
                            //
                        }
                    }
                }
            })
    }
}